<!-- 产品管理 -->
<template>
  <div class="product-management">
    <div class="title-section">
      <h2>产品管理</h2>
      <div>
        <button class="btn-secondary" @click="handleExport">导出</button>
        <button class="btn-primary" style="margin-left: 8px;" @click="openCreateDialog">新建</button>
      </div>
    </div>

    <!-- 筛选区域 -->
    <div class="controls-section">
      <div class="filters">
        <div class="filter-item">
          <label>产品编码</label>
          <input v-model.trim="filters.productCode" type="text" placeholder="请输入产品编码">
        </div>
        <div class="filter-item">
          <label>产品名称</label>
          <input v-model.trim="filters.productName" type="text" placeholder="请输入产品名称">
        </div>
        <div class="filter-item">
          <label>来源类型</label>
          <select v-model="filters.sourceType">
            <option value="">全部</option>
            <option v-for="opt in sourceTypeOptions" :key="opt" :value="opt">{{ opt }}</option>
          </select>
        </div>
        <div class="filter-item">
          <label>状态</label>
          <select v-model="filters.status">
            <option value="">全部</option>
            <option :value="0">启用</option>
            <option :value="1">停用</option>
          </select>
        </div>
      </div>
      <div class="actions">
        <button class="btn-primary" @click="handleSearch">搜索</button>
        <button class="btn-secondary" @click="handleReset">重置</button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <table>
        <thead>
        <tr>
          <th><input type="checkbox" v-model="selectAll" @change="toggleSelectAll"></th>
          <th>产品名称</th>
          <th>来源类型</th>
          <th>规格</th>
          <th>分类</th>
          <th>单位</th>
          <th>默认仓库</th>
          <th>当前库存</th>
          <th>采购价格</th>
          <th>销售价格</th>
          <th>制造成本</th>
          <th>状态</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(p, index) in tableData" :key="p.productId || index">
          <td><input type="checkbox" v-model="p.selected" @change="updateSelectAll"></td>
          <td class="link-style">
            <span class="name-link" @click="viewById(p)">{{ p.productName }}</span>
            <div class="sub">{{ p.productCode }}</div>
          </td>
          <td>{{ p.sourceType}}</td>
          <td>{{ p.specification}}</td>
          <td>{{ formatCategory(p.category) }}</td>
          <td>{{ p.unitName}}</td>
          <td>{{ p.warehouseName}}</td>
          <td>{{ formatNumber(p.currentStock) }}</td>
          <td>{{ formatMoney(p.purchasePrice) }}</td>
          <td>{{ formatMoney(p.salePrice) }}</td>
          <td>{{ formatMoney(p.costPrice) }}</td>
          <td>{{ formatStatus(p.status) }}</td>
          <td>
            <button class="btn-secondary" @click="openEditDialog(p)">编辑</button>
            <button class="btn-secondary" style="margin-left: 8px;" @click="handleDelete(p)">删除</button>
          </td>
        </tr>
        <tr v-if="!loading && tableData.length === 0">
          <td colspan="13" style="text-align:center;color:#909399;">暂无数据</td>
        </tr>
        <tr v-if="loading">
          <td colspan="13" style="text-align:center;color:#909399;">加载中...</td>
        </tr>
        </tbody>
      </table>
    </div>

    <!-- 底部区域 -->
    <div class="footer-section">
      <div class="footer-left">
        <input type="checkbox" v-model="selectAll" @change="toggleSelectAll">
        <label>全选</label>
      </div>
      <div class="pagination">
        <button @click="prevPage" :disabled="currentPage === 1">&lt;</button>
        <button v-for="page in totalPages" :key="page" :class="{ active: currentPage === page }" @click="goToPage(page)">{{ page }}</button>
        <button @click="nextPage" :disabled="currentPage === totalPages">&gt;</button>
        <select v-model.number="pageSize" @change="handleSizeChange">
          <option :value="10">10条/页</option>
          <option :value="20">20条/页</option>
          <option :value="50">50条/页</option>
        </select>
      </div>
    </div>

    <!-- 新增/编辑 弹窗 -->
    <div v-if="dialog.visible" class="dialog-mask">
      <div class="dialog">
        <div class="dialog-header">
          <span>{{ dialog.isEdit ? '编辑产品' : '新增产品' }}</span>
          <span class="dialog-close" @click="closeDialog">×</span>
        </div>
        <div class="dialog-body">
          <div class="form-grid">
            <div class="form-item">
              <label>产品编码</label>
              <input v-model.trim="dialog.form.productCode" type="text" placeholder="可不填，后端自动生成">
            </div>
            <div class="form-item required">
              <label>产品名称</label>
              <input v-model.trim="dialog.form.productName" type="text" placeholder="请输入产品名称">
            </div>
            <div class="form-item required">
              <label>来源类型</label>
              <select v-model="dialog.form.sourceType">
                <option disabled value="">请选择</option>
                <option v-for="opt in sourceTypeOptions" :key="opt" :value="opt">{{ opt }}</option>
              </select>
            </div>
            <div class="form-item">
              <label>规格</label>
              <input v-model.trim="dialog.form.specification" type="text" placeholder="请输入规格">
            </div>
            <div class="form-item">
              <label>分类</label>
              <select v-model.number="dialog.form.category">
                <option v-for="opt in categoryOptions" :key="opt.value" :value="opt.value">{{ opt.label }}</option>
              </select>
            </div>
            <div class="form-item">
              <label>单位名称</label>
              <input v-model.trim="dialog.form.unitName" type="text" placeholder="仅展示或简单录入">
            </div>
            <div class="form-item">
              <label>仓库名称</label>
              <input v-model.trim="dialog.form.warehouseName" type="text" placeholder="仅展示或简单录入">
            </div>
            <div class="form-item">
              <label>当前库存</label>
              <input v-model.number="dialog.form.currentStock" type="number" min="0" placeholder="0">
            </div>
            <div class="form-item">
              <label>采购价格</label>
              <input v-model.number="dialog.form.purchasePrice" type="number" min="0" step="0.01" placeholder="0.00">
            </div>
            <div class="form-item">
              <label>销售价格</label>
              <input v-model.number="dialog.form.salePrice" type="number" min="0" step="0.01" placeholder="0.00">
            </div>
            <div class="form-item">
              <label>成本价格</label>
              <input v-model.number="dialog.form.costPrice" type="number" min="0" step="0.01" placeholder="0.00">
            </div>
            <div class="form-item required">
              <label>状态</label>
              <select v-model.number="dialog.form.status">
                <option :value="0">启用</option>
                <option :value="1">停用</option>
              </select>
            </div>
          </div>
          <div v-if="dialog.error" class="form-error">{{ dialog.error }}</div>
        </div>
        <div class="dialog-footer">
          <button class="btn-secondary" @click="closeDialog">取消</button>
          <button class="btn-primary" style="margin-left: 8px;" :disabled="dialog.submitting" @click="submitDialog">{{ dialog.submitting ? '提交中...' : '保存' }}</button>
        </div>
      </div>
    </div>

    <!-- 详情 弹窗 -->
    <div v-if="detail.visible" class="dialog-mask">
      <div class="dialog">
        <div class="dialog-header">
          <span>产品详情</span>
          <span class="dialog-close" @click="closeDetail">×</span>
        </div>
        <div class="dialog-body">
          <div v-if="detail.loading" style="text-align:center;color:#909399;">加载中...</div>
          <div v-else class="detail-grid">
            <div class="detail-item"><label>产品名称</label><span>{{ detail.data.productName || '-' }}</span></div>
            <div class="detail-item"><label>产品编码</label><span>{{ detail.data.productCode || '-' }}</span></div>
            <div class="detail-item"><label>来源类型</label><span>{{ detail.data.sourceType || '-' }}</span></div>
            <div class="detail-item"><label>规格</label><span>{{ detail.data.specification || '-' }}</span></div>
            <div class="detail-item"><label>分类</label><span>{{ formatCategory(detail.data.category) }}</span></div>
            <div class="detail-item"><label>单位</label><span>{{ detail.data.unitName || '-' }}</span></div>
            <div class="detail-item"><label>默认仓库</label><span>{{ detail.data.warehouseName || '-' }}</span></div>
            <div class="detail-item"><label>当前库存</label><span>{{ formatNumber(detail.data.currentStock) }}</span></div>
            <div class="detail-item"><label>采购价格</label><span>{{ formatMoney(detail.data.purchasePrice) }}</span></div>
            <div class="detail-item"><label>销售价格</label><span>{{ formatMoney(detail.data.salePrice) }}</span></div>
            <div class="detail-item"><label>成本价格</label><span>{{ formatMoney(detail.data.costPrice) }}</span></div>
            <div class="detail-item"><label>状态</label><span>{{ formatStatus(detail.data.status) }}</span></div>
          </div>
        </div>
        <div class="dialog-footer">
          <button class="btn-primary" @click="closeDetail">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { pageProducts, createProduct, updateProduct, deleteProductById, getProductById, exportProducts } from '@/api/product'

export default {
  name: 'ProductManagement',
  data() {
    return {
      loading: false,
      selectAll: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      // 过滤条件
      filters: {
        productCode: '',
        productName: '',
        sourceType: '',
        status: ''
      },
      sourceTypeOptions: ['自制', '委外', '采购'],
      categoryOptions: [
        { value: 0, label: '成品' },
        { value: 1, label: '半成品' },
        { value: 2, label: '残次品' }
      ],
      // 弹窗状态
      dialog: {
        visible: false,
        isEdit: false,
        submitting: false,
        error: '',
        form: {
          productId: undefined,
          productCode: '',
          productName: '',
          sourceType: '',
          specification: '',
          category: 0,
          unitName: '',
          warehouseName: '',
          currentStock: 0,
          purchasePrice: 0,
          salePrice: 0,
          costPrice: 0,
          status: 0
        }
      },
      // 详情
      detail: {
        visible: false,
        loading: false,
        data: {}
      }
    }
  },
  computed: {
    totalPages() {
      return Math.max(1, Math.ceil(this.total / this.pageSize))
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    async fetchData() {
      this.loading = true
      try {
        const params = {
          pageNo: this.currentPage,
          pageSize: this.pageSize,
          productCode: this.filters.productCode || undefined,
          productName: this.filters.productName || undefined,
          sourceType: this.filters.sourceType || undefined,
          status: this.filters.status === '' ? undefined : this.filters.status
        }
        const res = await pageProducts(params)
        const payload = res?.data
        const pageData = payload?.data || payload
        const records = pageData?.records || []
        const total = pageData?.total || 0
        this.tableData = (records || []).map(r => ({
          ...r,
          // 兼容不同字段命名或嵌套返回
          unitName: r.unitName ?? r.unit_name ?? r.unit?.unitName ?? r.unit?.name ?? '',
          warehouseName: r.warehouseName ?? r.warehouse_name ?? r.warehouse?.warehouseName ?? r.warehouse?.name ?? '',
          selected: false
        }))
        this.total = total
        this.updateSelectAll()
      } catch (e) {
      } finally {
        this.loading = false
      }
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchData()
    },
    handleReset() {
      this.filters = { productCode: '', productName: '', sourceType: '', status: '' }
      this.currentPage = 1
      this.fetchData()
    },
    toggleSelectAll() {
      this.tableData.forEach(row => { row.selected = this.selectAll })
    },
    updateSelectAll() {
      if (this.tableData.length === 0) {
        this.selectAll = false
        return
      }
      this.selectAll = this.tableData.every(row => row.selected)
    },
    prevPage() { if (this.currentPage > 1) { this.currentPage--; this.fetchData() } },
    nextPage() { if (this.currentPage < this.totalPages) { this.currentPage++; this.fetchData() } },
    goToPage(page) { if (page !== this.currentPage) { this.currentPage = page; this.fetchData() } },
    handleSizeChange() { this.currentPage = 1; this.fetchData() },

    formatMoney(v) {
      const n = Number(v || 0)
      return n.toFixed(2)
    },
    formatNumber(v) {
      const n = Number(v || 0)
      return Number.isFinite(n) ? n : 0
    },
    formatStatus(s) {
      if (s === 0 || s === '0') return '启用'
      if (s === 1 || s === '1') return '停用'
      return '-'
    },
    formatCategory(c) {
      const map = { 0: '成品', 1: '半成品', 2: '残次品' }
      if (c === 0 || c === 1 || c === 2) return map[c]
      const num = Number(c)
      if ([0,1,2].includes(num)) return map[num]
      return c || '-'
    },

    // 弹窗相关
    resetDialogForm() {
      this.dialog.form = {
        productId: undefined,
        productCode: '',
        productName: '',
        sourceType: '',
        specification: '',
        category: 0,
        unitName: '',
        warehouseName: '',
        currentStock: 0,
        purchasePrice: 0,
        salePrice: 0,
        costPrice: 0,
        status: 0
      }
      this.dialog.error = ''
    },
    openCreateDialog() {
      this.dialog.isEdit = false
      this.resetDialogForm()
      this.dialog.visible = true
    },
    async openEditDialog(row) {
      try {
        this.dialog.isEdit = true
        this.dialog.error = ''
        const detailRes = await getProductById(row.productId)
        const detail = (detailRes?.data && detailRes.data.data) || detailRes?.data || row
        this.dialog.form = {
          productId: detail.productId,
          productCode: detail.productCode || '',
          productName: detail.productName || '',
          sourceType: detail.sourceType || '',
          specification: detail.specification || '',
          category: Number(detail.category ?? 0),
          unitName: detail.unitName || '',
          warehouseName: detail.warehouseName || '',
          currentStock: Number(detail.currentStock || 0),
          purchasePrice: Number(detail.purchasePrice || 0),
          salePrice: Number(detail.salePrice || 0),
          costPrice: Number(detail.costPrice || 0),
          status: Number(detail.status ?? 0)
        }
        this.dialog.visible = true
      } catch (e) {
      }
    },
    closeDialog() {
      if (this.dialog.submitting) return
      this.dialog.visible = false
    },
    validateDialogForm() {
      if (!this.dialog.form.productName) {
        this.dialog.error = '请填写产品名称'
        return false
      }
      if (!this.dialog.form.sourceType) {
        this.dialog.error = '请选择来源类型'
        return false
      }
      this.dialog.error = ''
      return true
    },
    async submitDialog() {
      if (!this.validateDialogForm()) return
      this.dialog.submitting = true
      try {
        const payload = { ...this.dialog.form }
        if (this.dialog.isEdit) {
          await updateProduct(payload)
        } else {
          if (!payload.productCode) delete payload.productCode
          delete payload.productId
          await createProduct(payload)
        }
        this.dialog.visible = false
        this.fetchData()
      } catch (e) {
      } finally {
        this.dialog.submitting = false
      }
    },

    async handleDelete(row) {
      const ok = window.confirm(`确认删除产品：${row.productName}？`)
      if (!ok) return
      try {
        await deleteProductById(row.productId)
        this.fetchData()
      } catch (e) {}
    },

    async handleExport() {
      try {
        const params = {
          productCode: this.filters.productCode || undefined,
          productName: this.filters.productName || undefined,
          sourceType: this.filters.sourceType || undefined,
          status: this.filters.status === '' ? undefined : this.filters.status
        }
        const res = await exportProducts(params)
        const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        const fileName = `商品信息_${new Date().toISOString().slice(0,10)}.xlsx`
        this.downloadBlob(blob, fileName)
      } catch (e) {}
    },

    downloadBlob(blob, fileName) {
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = fileName
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      window.URL.revokeObjectURL(url)
    },

    // 详情
    async viewById(row) {
      try {
        this.detail.visible = true
        this.detail.loading = true
        this.detail.data = {}
        const res = await getProductById(row.productId)
        const data = (res?.data && res.data.data) || res?.data || {}
        // 字段兼容
        this.detail.data = {
          ...data,
          unitName: data.unitName ?? data.unit_name ?? data.unit?.unitName ?? data.unit?.name ?? '',
          warehouseName: data.warehouseName ?? data.warehouse_name ?? data.warehouse?.warehouseName ?? data.warehouse?.name ?? ''
        }
      } catch (e) {
      } finally {
        this.detail.loading = false
      }
    },
    closeDetail() {
      if (this.detail.loading) return
      this.detail.visible = false
    }
  }
}
</script>

<style scoped>
.product-management { padding: 20px; background-color: #f5f7fa; }
.title-section { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.title-section h2 { font-size: 20px; font-weight: bold; }

.controls-section { display: flex; justify-content: space-between; flex-wrap: wrap; gap: 16px; padding: 20px; background-color: #fff; border-radius: 8px; margin-bottom: 20px; align-items: center; }
.filters { display: flex; flex-wrap: wrap; gap: 16px; align-items: center; }
.filter-item { display: flex; align-items: center; gap: 8px; }
.filter-item label { font-size: 14px; white-space: nowrap; }
.filter-item input, .filter-item select { padding: 8px; border: 1px solid #dcdfe6; border-radius: 4px; width: 150px; }
.actions { display: flex; gap: 10px; }
.btn-primary { background-color: #409eff; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer; }
.btn-secondary { background-color: #fff; color: #606266; border: 1px solid #dcdfe6; padding: 8px 16px; border-radius: 4px; cursor: pointer; }

.table-section { background-color: #fff; padding: 20px; border-radius: 8px; }
table { width: 100%; border-collapse: collapse; }
th, td { padding: 12px; text-align: left; border-bottom: 1px solid #ebeef5; }
th { background-color: #f8f9fa; }
.link-style { color: #409eff; cursor: pointer; }
.name-link { color: #409eff; }
.sub { color: #666; font-size: 12px; }
.sortable-header { cursor: pointer; position: relative; }
.tooltip { position: absolute; top: -25px; left: 50%; transform: translateX(-50%); background: #f44336; color: white; padding: 4px 8px; border-radius: 4px; font-size: 12px; white-space: nowrap; }

.footer-section { display: flex; justify-content: space-between; align-items: center; margin-top: 20px; background-color: #fff; padding: 10px 20px; border-radius: 8px; }
.footer-left { display: flex; align-items: center; gap: 8px; }
.pagination { display: flex; align-items: center; gap: 8px; }
.pagination button { padding: 6px 12px; border: 1px solid #dcdfe6; background-color: #fff; cursor: pointer; border-radius: 4px; }
.pagination button.active { background-color: #409eff; color: white; border-color: #409eff; }
.pagination select { padding: 6px; border: 1px solid #dcdfe6; border-radius: 4px; }

/* 简易弹窗样式 */
.dialog-mask { position: fixed; inset: 0; background: rgba(0,0,0,0.35); display: flex; align-items: center; justify-content: center; z-index: 1000; }
.dialog { width: 760px; max-width: calc(100vw - 40px); background: #fff; border-radius: 8px; overflow: hidden; }
.dialog-header { display: flex; align-items: center; justify-content: space-between; padding: 12px 16px; border-bottom: 1px solid #ebeef5; font-weight: 600; }
.dialog-close { cursor: pointer; font-size: 20px; line-height: 20px; }
.dialog-body { padding: 16px; }
.dialog-footer { padding: 12px 16px; border-top: 1px solid #ebeef5; display: flex; justify-content: flex-end; }
.form-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px 16px; }
.form-item { display: flex; flex-direction: column; gap: 6px; }
.form-item.required label::after { content: '*'; color: #f56c6c; margin-left: 4px; }
.form-item input, .form-item select { padding: 8px; border: 1px solid #dcdfe6; border-radius: 4px; }
.form-error { color: #f56c6c; margin-top: 8px; }

/* 详情布局 */
.detail-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px 16px; }
.detail-item { display: flex; align-items: center; gap: 8px; }
.detail-item label { width: 96px; color: #909399; text-align: right; }
.detail-item span { color: #303133; }
</style>


